package com.wangyk.pay.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wangyk.pay.service.WeChatPayService;
import com.wangyk.pay.pojo.weChatPayPojo.UnifyOrderRequest;
import com.wangyk.rabbitmqcommon.VO.ResultVO;
import com.wangyk.rabbitmqcommon.utils.ResultVOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * @ClassName WeChatPayController
 * @Description TODO(微信支付接口)
 * @author wangyk
 * @Date 2018年9月18日 下午3:10:30
 * @version 1.0.0
 */
@Controller
@CrossOrigin
@RequestMapping("/wechatPay")
public class WeChatPayController
{
    private Logger logger = LogManager.getLogger(WeChatPayController.class);
    
    @Resource
    private WeChatPayService weChatPayService;
    
    @Resource
    private HttpServletRequest request;
    
    /**
     * @Description (调用微信支付的接口)
     * @author wangyk
     * @param unifyOrderReq
     * @return
     */
    @RequestMapping("/wechatPay.do")
    @ResponseBody
    public ResultVO wechatPay(@RequestBody UnifyOrderRequest unifyOrderRequest)
    {
        ResultVO resultVO = new ResultVO();
        try
        {
            String weixinIdStr = request.getHeader("userId");
            if (StringUtils.isEmpty(weixinIdStr))
            {
                Integer weixinId = Integer.parseInt(weixinIdStr);
                resultVO = weChatPayService.wechatPay(weixinId, unifyOrderRequest);
            }
            else
            {
                return ResultVOUtils.error();
            }
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
        }
        return resultVO;
    }

    /**
     *
     * @Description 微信生成支付二维码
     * @author wangk
     * @param user
     * @return
     */
    @RequestMapping("/weixin_pay.do")
    @ResponseBody
    public ResultVO weiXinPay(@ModelAttribute UnifyOrderRequest req)
    {

        ResultVO resultVO = new ResultVO();
        try
        {
            req.setTotal_fee(1);
            resultVO = weChatPayService.weiXinPay(req);

        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
        }
        return resultVO;
    }

    /**
     *
     * @Description 微信支付成功回调
     * @author wangk
     * @param user
     * @return
     */
    @RequestMapping("/external/weixin_pay_success.do")
    @ResponseBody
    public void weixinPaySuccess(HttpServletRequest request, HttpServletResponse response)
    {
        try
        {
            weChatPayService.weixinPaySuccess(request, response);
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
        }
    }
}
